package jk.zmn.thread.syn;


/**
 * @author 张梦楠
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2018/5/2617:11
 * @blog www.itzmn.com
 *
 *  锁
 *
 */
public class SynThreadDemo1 {

     public static void main(String[] args) {

         webtest web12306 = new webtest();
         //代理类
         Thread demo1 = new Thread(web12306, "黄牛1");
         Thread demo2 = new Thread(web12306, "黄牛2");
         Thread demo3 = new Thread(web12306, "黄牛3");
         demo1.start();
         demo2.start();
         demo3.start();
     }

}

class webtest implements Runnable{
    private int num=10;//50张票

    public boolean flag=true;
    @Override
    public void run() {
        while (flag){
           test3();
        }
    }
    public  void test3() {//锁代码块
        synchronized (this) {
            if (num <= 0) {
                flag = false;
                return;
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "售出了第" + num-- + "张票");
        }
    }
    public synchronized void test2() { //方法锁
        if (num<=0){
            flag = false;
            return;
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"售出了第"+num--+"张票");

    }

    public  void test1() { //不安全
        if (num<=0){
            flag = false;
            return;
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"售出了第"+num+"张票");
        num--;
    }

}